<template>
  <div class="logins">
    <div class="head rb">
      <i class="text1">{{ flog == 1 || flog == 3 ? "登录" : "注册" }}</i>
      <div class="Lright row">
        <i class="text2 pointer" @click="toPhone()">{{
          flog == 1 ? "邮箱验证码登录" : "用户密码登录"
        }}</i>
        <div class="ma hover">
          <img width="80" height="80" src="@/assets/imgs/wx.png" alt="" />
        </div>
      </div>
    </div>
    <!--<div class="main">
      <div v-if="flog == 1 || flog == 2">
        <el-input  v-if="flog == 1" v-model="loginInfo.username" placeholder="用户名"></el-input>
        <el-input
          v-if="flog == 2"
          v-model="loginInfo.phone"
          placeholder="手机号"
        ></el-input>
        <el-input
          show-password
          v-model="loginInfo.password"
          placeholder="密码"
        ></el-input>
      </div>
      <div v-else>
        <el-input v-model="phoneLogin.phone" placeholder="手机号"></el-input>
        <el-input v-model="phoneLogin.test" placeholder="验证码">
          <template slot="append"
            ><i class="pointer">{{ phoneLogin.placeh }}</i></template
          ></el-input
        >
      </div>

      <div class="check rb">
        <el-checkbox v-model="self">下次自动登录</el-checkbox
        ><i class="hover">忘记密码</i>
      </div>
      <div class="mainB tc hovers" @click="submit()">
        {{ flog == 1 || flog == 3 ? "登录" : "注册" }}
      </div>
      <div class="tc">
        <i class="otherB tc hover" @click="change()">{{
          flog == 1 || flog == 3 ? "注册" : "登录"
        }}</i>
      </div>

      <div class="more ra">
        <i class="hover el-icon-ice-cream-square">微信</i>
        <i class="hover el-icon-ice-cream-round">QQ</i>
      </div>
    </div> -->

    <div class="main">
      <el-form :model="loginInfo" status-icon :rules="rules" ref="ruleForm">
        <el-form-item prop="name" v-if="flog == 2">
          <!-- label="用户名" -->
          <el-input
            v-model.trim="loginInfo.name"
            placeholder="真实姓名"
          ></el-input>
        </el-form-item>

        <!-- label-width="100px" -->
        <el-form-item prop="username" v-if="flog == 1 || flog == 2">
          <!-- label="用户名" -->
          <el-input
            v-model.trim="loginInfo.username"
            placeholder="用户名"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password" v-if="flog == 1 || flog == 2">
          <el-input
            show-password
            v-model.trim="loginInfo.password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="flog == 2" prop="phone">
          <el-input
            v-model.number="loginInfo.phone"
            placeholder="手机号"
            class="mt2"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="flog == 2 || flog == 3" prop="email">
          <el-input
            v-model.trim="loginInfo.email"
            placeholder="QQ邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item prop="test" v-if="flog == 3 || flog == 2">
          <el-input v-model.trim="loginInfo.test" placeholder="邮箱验证码(4位)">
            <template slot="append"
              ><el-button
                :disabled="sendFlog != 1"
                class="pointer"
                @click="send()"
                >{{ loginInfo.placeh }}</el-button
              ></template
            ></el-input
          >
        </el-form-item>
      </el-form>

      <div class="check rb">
        <el-checkbox v-model="self">下次自动登录</el-checkbox
        ><i class="hover">忘记密码</i>
      </div>
      <el-button class="tologin colorw" type="text" @click="submit()">
        {{ flog == 1 || flog == 3 ? "登录" : "注册" }}
      </el-button>
      <div class="tc otherB">
        <el-button type="text" @click="change()">
          {{ flog == 1 || flog == 3 ? "注册" : "登录" }}
        </el-button>
      </div>

      <div class="more ra">
        <i class="hover el-icon-ice-cream-square">微信</i>
        <i class="hover el-icon-ice-cream-round">QQ</i>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(
          new Error(
            "密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线。"
          )
        );
      } else {
        if (/^[a-zA-Z]\w{5,17}$/.test(this.loginInfo.password)) {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        if (
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
            this.loginInfo.phone
          )
        ) {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    const validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入QQ邮箱"));
      } else {
        if (/^\d+@qq.com$/i.test(this.loginInfo.email)) {
          this.$refs.ruleForm.validateField("checkPass");
        } else {
          callback(new Error("QQ邮箱格式不正确"));
        }
        callback();
      }
    };
    const validateTest = (rule, value, callback) => {
      if (this.loginInfo.email == "") {
        callback(new Error("请先输入上一栏的QQ邮箱"));
      } else if (value === "") {
        callback(new Error("请输入4位验证码"));
      } else {
        if (/^\w{4}$/.test(this.loginInfo.test)) {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    return {
      flog: 1, //1：登录；2：注册;3:手机验证码登录
      loginInfo: {
        name: "",
        username: "",
        password: "",
        phone: "",
        test: "",
        placeh: "发送",
        admin: false,
      },
      self: 1,
      sendFlog: 1,
      rules: {
        userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ validator: validatePass, trigger: "blur" }],
        phone: [{ validator: validatePhone, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }],
        test: [{ validator: validateTest, trigger: "blur" }],
      },
    };
  },
  methods: {
    clear() {
      this.loginInfo = {
        name: "",
        username: "user",
        password: "123456",
        phone: "",
        email: "",
        test: "",
        placeh: "发送",
        admin: false,
      };
    },

    submit() {
      switch (this.flog) {
        //1：登录；2：注册;3:手机验证码登录
        case 1:
          if (this.loginInfo.username == "" || this.loginInfo.password == "") {
            this.$message.warning("请填写完整!");
            return;
          }

          this.$axios
            .post(
              "/myLoginForm?username=" +
                this.loginInfo.username +
                "&password=" +
                this.loginInfo.password
            )
            .then((res) => {
              console.log("login: res= ", res);

              if (res.data.code == 200) {
                let userInfo = {};
                console.log("logins: data: ", res.data);
                this.$set(userInfo, "token", res.data.token);
                this.$set(userInfo, "userId", res.data.userId);
                let dbRoles = [];
                res.data.authorities.forEach((item) => {
                  dbRoles.push(item.authority);
                });
                this.$set(userInfo, "roles", dbRoles);
                this.$store.commit("user/setUserInfo", userInfo);
                // console.log("获得token为:" + localStorage.getItem("token"));
                // console.log("userId : :" + this.$store.state.user.user.userId);

                // 获取用户角色，是否是管理员
                // this.$axios
                //   .post("/checkAdminByUserId", userInfo)
                //   .then((res) => {
                //     if (res.data.code == 201) {
                //       this.$router.push("adminIndex");
                //       return;
                //     }
                //   });

                if (this.$route.query.url) {
                  this.$router.push({
                    path: this.$route.query.url,
                    query: { bookId: this.$route.query.bookId },
                  });
                }

                this.$router.push("/index");
              } else {
                this.$message.warning(res.data.message);
                this.loginInfo.password = "";
              }
            });
          break;
        case 2:
          if (
            this.loginInfo.name == "" ||
            this.loginInfo.username == "" ||
            this.loginInfo.password == "" ||
            this.loginInfo.phone == "" ||
            this.loginInfo.email == "" ||
            this.loginInfo.test == ""
          ) {
            this.$message.warning("请填写完整!");
            return;
          }

          console.log("register:loginInfo=", this.loginInfo);
          this.$axios
            .post("index/sys/user/register", this.loginInfo)
            .then(({ data }) => {
              if (data.code == 200 || data.code == 201) {
                this.$message.success("恭喜！注册成功！");
                this.clear();
                this.flog = 1;
              } else {
                this.$message.warning(data.data);
              }
              console.log("res : ", data);
            });
          break;
        case 3:
          if (this.loginInfo.email == "" || this.loginInfo.test == "") {
            this.$message.warning("请填写完整!");
            return;
          }
          break;
        default:
          this.clear();
          break;
      }
    },
    change() {
      this.flog = this.flog == 1 || this.flog == 3 ? 2 : 1;
      this.clear();
    },
    toPhone() {
      this.flog = this.flog == 3 || this.flog == 2 ? 1 : 3;
      this.clear();
    },
    send() {
      console.log("send");
      if (this.sendFlog != 1 || this.loginInfo.email == "") {
        console.log("return");
        return;
      } else {
        console.log("start");
        this.$axios
          .get("index/sendMailTest?email=" + this.loginInfo.email)
          .then(({ data }) => {
            // console.log("sendMailTest : ", data);
            if (data.code == 201) {
              this.$message.success("已发送");
            } else {
              this.$message.warning("发送失败");
            }
          });
        this.sendFlog = 0;
        if (this.loginInfo.placeh == "发送") {
          // console.log("this.placeh = 10");
          this.loginInfo.placeh = 60;
        }
        const _this = this;
        let setI = setInterval(() => {
          // console.log("setInterval");
          // console.log("this.loginInfo.placeh:", _this.loginInfo.placeh);
          _this.loginInfo.placeh--;
          if (_this.loginInfo.placeh <= 0) {
            // console.log("this.loginInfo.placeh <= 0");
            _this.sendFlog = 1;
            _this.loginInfo.placeh = "发送";
            clearInterval(setI);
          }
        }, 1000);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.logins {
  width: 380px;
  // background: rgb(105, 99, 99);
}
.head {
  margin-bottom: 40px;
  .text1 {
    font-size: 28px;
    color: rgb(72, 70, 70);
    font-weight: 500;
  }
  .Lright {
    margin-top: 20px;
    position: relative;
    .text2 {
      font-size: 10px;
      color: lightgray;
      margin-right: 120px;
    }
    .ma {
      position: absolute;
      left: 84px;
      bottom: -30px;
    }
    .ma::after {
      content: "";
      width: 0;
      height: 0;
      top: 0;
      left: 0;
      position: absolute;
      border: 40px solid white;
      border-top-color: transparent;
      // border-bottom-color: transparent;
      // border-left-color: transparent;
      border-right-color: transparent;
    }
  }
}
.main {
  width: 320px;
  .check {
    margin-top: 40px;
    margin-bottom: 30px;
  }
  .tologin {
    width: 100%;
    line-height: 2;
    background: rgb(96, 190, 222);
    color: white;
  }
  .tologin:hover {
    background: rgb(205, 44, 44);
  }
  .otherB {
    line-height: 2;
    margin-bottom: 20px;
  }
  .mt2 {
    margin-top: 20px;
  }
  .colorw {
    color: white;
  }
}
</style>